import * as React from 'react';
import { BrowserRouter, Route, Routes } from 'react-router-dom';
import { baseRoutes, routes } from './index';
import Loading from '@/components/Loading/loading';
import { WitRouterProp } from '@/router/types';
import { lazyLoad, RouterBeforeEach } from '@/utils/router';

// 获取路由，多级路由
const getRouter = (routeList: Array<WitRouterProp>): React.ReactNode =>
  routeList.map(({ path, children, component }) => {
    return (
      <Route
        path={path}
        element={
          component && component !== 'Layout' ? <RouterBeforeEach>{lazyLoad(component)}</RouterBeforeEach> : undefined
        }
        key={path}
      >
        {children ? getRouter(children) : undefined}
      </Route>
    );
  });

const getBaseRouter = (routeList: Array<WitRouterProp>): React.ReactNode =>
  routeList.map(({ path, children, component }) => {
    return (
      <Route path={path} element={component && component !== 'Layout' ? lazyLoad(component) : undefined} key={path}>
        {children ? getBaseRouter(children) : undefined}
      </Route>
    );
  });

export const RouterView = () => (
  <React.Suspense fallback={<Loading />}>
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<RouterBeforeEach>{lazyLoad('Layout')}</RouterBeforeEach>}>
          {/* 需要验证的路由 */}
          {getRouter(routes)}
        </Route>
        {/* 无验证路由 */}
        {getBaseRouter(baseRoutes)}
      </Routes>
    </BrowserRouter>
  </React.Suspense>
);
